<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleBeforeClose"
    >
      <!-- :rules="rules" -->
      <el-form
        :model="goods"
        ref="ruleForm"
        :rules="rules"
        label-width="6.25rem"
        class="demo-ruleForm"
      >
        <el-form-item v-if="!isAdd" label="商品编号" prop="pid">
          <!-- :readonly="!isAdd" -->
          <el-input v-model="goods.pid" readonly></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="pname">
          <el-input v-model="goods.pname"></el-input>
        </el-form-item>
        <el-form-item label="商品原价" prop="marketPrice">
          <el-input v-model.number="goods.marketPrice"></el-input>
        </el-form-item>
        <el-form-item label="商品现价" prop="shopPrice">
          <el-input v-model.number="goods.shopPrice"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <!-- <el-image
            style="width: 90%; height: 200px"
            :src="'http://127.0.0.1:8080/image/' + goods.image"
          ></el-image> -->
          <el-upload
            class="avatar-uploader"
            :action="'http://localhost:8080/file/uploadfile/' + goods.csid"
            name="file"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="goods.image"
              :src="'http://127.0.0.1:8080/image/' + goods.image"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否热门" prop="isHot">
          <el-switch
            style="display: block"
            v-model="goods.isHot"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="热门商品"
            inactive-text="冷门商品"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="商品描述" prop="pdesc">
          <el-input
            type="textarea"
            :rows="5"
            placeholder="请输入内容"
            v-model.trim="goods.pdesc"
          >
          </el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handlerClose">取 消</el-button>
        <el-button type="primary" @click="handlerSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { queryProductById, saveProduct } from "@/api/productApi.js";
export default {
  props: {
    title: String,
    isAdd: Boolean,
    dialogVisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      goods: {
        pid: "",
        pname: "",
        marketPrice: 0,
        shopPrice: 0,
        image: "",
        pdesc: "",
        isHot: 1,
        csid: 1,
      },
      rules: {
        pname: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        marketPrice: [
          { required: true, message: "请输入商品原价", trigger: "blur" },
        ],
        shopPrice: [
          { required: true, message: "请输入商品现价", trigger: "blur" },
        ],
        pdesc: [{ required: true, message: "请输入商品描述", trigger: "blur" }],
        image: [{ required: true, message: "请上传商品图片", trigger: "blur" }],
      },
    };
  },
  methods: {
    /**
     * 去修改商品信息
     */
    async toEditAndAdd(pid) {
      if (pid) {
        try {
          const result = await queryProductById(pid);

          if (result.status == 200) {
            this.goods = result.data;
            console.log(this.goods);
          } else {
            this.$message.error(result.msg);
          }
        } catch (err) {
          this.$message.error(err.message);
        }
        // console.log("修改商品...",pid);
      } else {
        // console.log("新增商品...");
        this.init();
        console.log(this.goods);
      }
    },
    /**
     * 保存
     */
    handlerSave() {
      this.$refs.ruleForm
        .validate()
        .then(async () => {
          const result = await saveProduct(this.goods);
          if (result.status == 200) {
            this.$message({
              message: "保存成功",
              type: "success",
              duration: 1000,
              onClose: () => {
                this.$emit("handlerCloseDialog");
              },
            });
          } else {
            this.$message({
              message: "保存失败",
              type: "error",
              duration: 1000,
              onClose: () => {
                this.$emit("handlerCloseDialog");
              },
            });
          }
        })
        .catch((err) => {
          this.$message.error("输入保存的数据不合法!");
        });
    },
    /*
        x的关闭
        */
    handleBeforeClose() {
      this.$emit("handlerCloseDialog");
    },
    handlerClose() {
      this.$emit("handlerCloseDialog");
    },
    /**
     * 文件上传成功
     */
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(res, file);
      if (res.status == 200) {
        this.goods.image = res.data;
      } else {
        this.$message.error("上传文件失败!");
      }
    },
    /*
     上传之前的校验
    */
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      // const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG或者PNG 格式!");
      }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!');
      // }
      return isJPG;
    },

    init() {
      this.goods = {
        pid: "",
        pname: "",
        marketPrice: 0,
        shopPrice: 0,
        image: "",
        pdesc: "",
        isHot: 1,
        csid: 1,
      };
    },
  },
};
</script>

<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
